package me.leetcodepractice;

public class E08Leetcode876 {
    // 找链表的中间节点
    // 快慢指针法
    public ListNode middleNode(ListNode head) {
        ListNode p1 = head;
        ListNode p2 = head;
        // 当p2的下一节点或p2本身为null时，退出循环
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next;
            p2 = p2.next;
        }
        return p1;
    }

    public static void main(String[] args) {
        ListNode head1 = ListNode.of(1, 2, 3, 4, 5);
        ListNode head2 = ListNode.of(1, 2, 3, 4, 5, 6);
        System.out.println(new E08Leetcode876().middleNode(head1));
        System.out.println("---------------");
        System.out.println(new E08Leetcode876().middleNode(head2));
    }
}
